/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.example.transport.tcp;

import com.inyourcode.core.serialization.api.SerializerType;
import com.inyourcode.core.transport.api.JConnection;
import com.inyourcode.core.transport.api.payload.BytesHolder;
import com.inyourcode.core.transport.session.BasicTcpConnector;
import com.inyourcode.core.transport.session.IllegalHandlerException;
import com.inyourcode.core.transport.session.MessageCoderFactory;
import com.inyourcode.core.transport.session.RequestContext;
import com.inyourcode.core.transport.session.SessionHandlerMapping;
import com.inyourcode.core.transport.session.api.IMessageCoder;
import com.inyourcode.example.protobuf.LoginProto;
import com.inyourcode.example.service.InvokeId;
import com.inyourcode.example.service.handler.TestProtoHandler;
import com.inyourcode.core.transport.api.UnresolvedAddress;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author JackLei
 */
public class TestTcpClient {
    private static AtomicInteger traceIdGen = new AtomicInteger();
    private static Channel channel;

    public static void main(String[] args) throws IllegalHandlerException {
        BasicTcpConnector connector = new BasicTcpConnector();
        SessionHandlerMapping.mappingHandler(Arrays.asList(new TestProtoHandler()));
        JConnection connect = connector.connect(new UnresolvedAddress("127.0.0.1", 8999), true);
        connect.setReconnect(false);
        connect.operationComplete((ch) -> {
            channel = ch;
        });

        Thread thread = new Thread("T#CMD") {
            @Override
            public void run() {
                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                    String msg = null;
                    try {
                        msg = console.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (msg == null) {
                        break;
                    } else if ("login".equals(msg.toLowerCase())) {
                        LoginProto.C2L_ProtoTest.Builder body = LoginProto.C2L_ProtoTest.newBuilder();
                        body.setToken("readstar#@#$%%!!!!!");
                        RequestContext requestContext = new RequestContext(InvokeId.C2L_ProtoTest, traceIdGen.incrementAndGet(), body, SerializerType.PROTOBUF.value());

                        IMessageCoder messageParser = MessageCoderFactory.getMessageCoder(SerializerType.PROTOBUF.value());
                        BytesHolder jRequestPayload = messageParser.encode(requestContext);
                        channel.writeAndFlush(jRequestPayload).addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                if (channelFuture.isSuccess()) {

                                } else {
                                    channelFuture.cause().printStackTrace();
                                }
                            }
                        });
                    } else {
                        //do nothing
                    }
                }
            }
        };

        thread.start();
    }

}
